package com.wc;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @ClassName:LoginFilter
 * @Author: 鹿建文
 * @Date: 2022/4/13  - 16:11
 * @Describe:
 */
@WebFilter(urlPatterns = "/*")
public class LoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("*************filter");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String aim = request.getRequestURI();
        System.out.println(aim);
        HttpSession session = request.getSession();
        Object admin = session.getAttribute("admin");
        if(admin!=null || aim.contains("login.ftl") || aim.contains("error.ftl")|| aim.contains("admin")){
            //果用户已经登录or正在访问登录页面时or访问error页面时，请求放行
            filterChain.doFilter(request,response);
        }else{
            //如果没有登录跳转到登录页面让用户登录
            response.sendRedirect("login.ftl");
        }
    }
}
